import { login, pwdlogin, logout } from '@/api/login'
import { getUserInfo } from "@/api/sys/user"
import { getMenu } from "@/api/sys/menu"
import { getToken, setToken, removeToken } from '@/utils/auth'
// import { constantRoutes } from '@/router'
import Layout from '@/layout/index'
import { getStore } from '@/utils/store'

const user = {
  state: {
    token: getToken(),
    roles: [],
    permissions: [],
    userInfo: {},
    routes: [],
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      // state.routes = constantRoutes.concat(routes)
      state.routes = routes
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_USERINFO: (state, data) => {
      state.userInfo = data
    },
  },
  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid).then(res => {
          setToken(res.token)
          commit('SET_TOKEN', res.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    pwdLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        pwdlogin(userInfo).then(res => {
          const token = `${res.token_type} ${res.access_token}`
          setToken(token)
          commit('SET_TOKEN', token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        const userName = getStore({
          name: "userName",
          type: 1
        })
        getUserInfo(userName).then(({ data }) => {
          if (data.roles && data.roles.length > 0) {
            commit('SET_ROLES', data.roles)
            commit('SET_PERMISSIONS', data.permissions)
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }
          commit('SET_USERINFO', data.sysUser)
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 退出系统
    LogOutByApi({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 退出系统
    LogOut({ commit }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_PERMISSIONS', [])
        removeToken()
        resolve()
      })
    },
    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },
    // 获取菜单
    GenerateRoutes({ commit }) {
      return new Promise(resolve => {
        // 向后端请求路由数据
        getMenu().then(({ data }) => {
          const addRouters = dealRouters(data)
          commit('SET_ROUTES', addRouters)
          resolve(addRouters)
        })
      })
    },
  }
}

function dealRouters(list) {
  let rows = []
  for (let item of list) {
    let children = []
    if (item.children && item.children.length) {
      for (let t of item.children) {
        if (t.menuType === "M") {
          children.push({
            path: t.path,
            name: t.menuName,
            icon: t.icon,
            component: (resolve) => require([`@/views${t.path}.vue`], resolve)
          })
        }
      }
    }
    rows.push({
      icon: item.icon,
      path: item.path,
      name: item.menuName,
      component: Layout,
      hidden: item.keepAlive,
      children: children
    })
  }
  return rows
}

export default user
